const mongoose = require('mongoose');
const User = require('../models/user.models');

exports.create = function (req,res,next) {
    const user = new User(req.body);
    user.save().then(data=>{
        res.json(data);
    });
};

exports.get = function (req,res,next) {
  var page = req.query.page || 1;
  var limit = req.query.limit || 5;
  User.paginate({}, { page: page, limit: limit }, function(err, result) {
    res.json(result.docs);
  });
};

exports.update = function (req,res,next) {
  const id = req.params.id;
  User.findByIdAndUpdate(id,{ $set:req.body },{ new:false }).then(data=>{
    res.json(data);//data:更新之前的数据
  })
};

exports.delete = function (req,res,next) {
  const id = req.params.id;
  User.findByIdAndRemove(id,function(err,doc){
    res.json({message:'ojbk',status:200});
  })
};

exports.list = function (req,res,next) {
  var page = req.body.page ? req.body.page : 1;
  var rows = req.body.rows ? req.body.rows : 5;
  var quertCondition = {};
 
  if(req.body.email && req.body.email.trim().length > 0){
    quertCondition={
      email : new RegExp(req.body.email,'i')
    }
  }
  User.paginate(quertCondition, { page: +page, limit: +rows }, function(err, result) {
    result.rows = result.docs;
    delete result.docs;
    res.json(result);
  });
};
